#pragma once

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <iostream>

#include "Log.hpp"
#include "LockGuard.hpp"
#include "nocopy.hpp"
#include "Inet_Addr.hpp"

using namespace LogModule;

// 错误类型
enum 
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

// 缺省
static const int g_socket = -1;
static const uint16_t g_port = 8888;

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t g_port) 
        :_sockfd(g_socket)
        ,_localport(g_port)
        ,_isrunning(false)
    {}

    ~UdpServer() 
    {
        if(_sockfd > g_socket)
            ::close(_sockfd);
    }

    void InitServer()
    {
        // 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error!\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd:%d\n", _sockfd);
        
        // bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success!\n");
    }

    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t m = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(m > 0)
            {
                inbuffer[m] = 0;
                // uint16_t peerport = ntohs(peer.sin_port);
                // std::string peerip = inet_ntoa(peer.sin_addr);

                Inet_Addr inet_addr(peer);

                std::cout << "[" << inet_addr.Ip() << " : " << inet_addr.Port() << "]# " << inbuffer << std::endl;
                std::string echo_string = "[udp_server echo]# ";
                echo_string += inbuffer;
                ssize_t s = ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr*)&peer, len);
                if(s < 0)
                {
                    LOG(WARNING, "sendto error\n");
                }
            }
            else
            {
                LOG(FATAL, "recvfrom error\n");
            }
        }
    }

private:
    int _sockfd;
    uint16_t _localport;
    bool _isrunning;
};